import {getPermission} from "@/api/login";
import Layout from "@/layout/index.vue";
import {getAccessToken} from "@/utils/auth";

export async function initDynamicRoutes(router) {
    /*    let cachedRoutes = localStorage.getItem('cachedDynamicRoutes');
        let dynamicRoutes;

        if (cachedRoutes) {
            dynamicRoutes = JSON.parse(cachedRoutes);
        } else {
            try {
                const response = await getPermission();
                dynamicRoutes = response.data;
                localStorage.setItem('cachedDynamicRoutes', JSON.stringify(dynamicRoutes));
            } catch (error) {
                console.error('Failed to fetch dynamic routes:', error);
                return;
            }
        }*/
    if (getAccessToken()) {
        let dynamicRoutes;
        try {
            const response = await getPermission();
            dynamicRoutes = response.data;
            // localStorage.setItem('cachedDynamicRoutes', JSON.stringify(dynamicRoutes));
        } catch (error) {
            console.error('Failed to fetch dynamic routes:', error);
            // 直接抛出错误信息
            throw '路由错误！';
        }
        const currentRoutes = router.getRoutes();
        const uniqueDynamicRoutes = dynamicRoutes.filter(route => {
            return !currentRoutes.some(existingRoute => existingRoute.path === route.path && existingRoute.name === route.name);
        });

        let root = {
            path: '/',
            // name: 'layout',
            component: Layout, // 修改为 Layout 组件
            children: [
                {
                    path: '',
                    name: 'home',
                    component: () => import( '@/views/basic/HomeView.vue')
                },
                {
                    path: 'change-password',
                    name: 'change-password',
                    component: () => import(/* webpackChunkName: "about" */ '@/views/basic/ChangePasswordView.vue')
                },
                {
                    path: 'about',
                    name: 'about',
                    component: () => import( '@/views/basic/AboutView.vue'),
                },]
        }
        uniqueDynamicRoutes.forEach(p => {
            const object = {
                path: p.path,
                name: p.name,
                component: () => import('@/views/' + p.component) // 使用异步组件的方式导入
            }
            root.children.push(object)
        })
        router.addRoute(root)
    }
}
